package com.education.wisdom.controller.app;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.education.common.utils.UUIDUtils;
import com.education.wisdom.feign.UserFeign;
import com.education.wisdom.pojo.CurrencyRecord;
import com.education.wisdom.service.ICurrencyRecordService;
import com.education.wisdom.service.IUserAccountService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@Controller
@RequestMapping("/iap")
public class IapController {

    @Autowired
    private IUserAccountService userAccountService;
    @Autowired
    private ICurrencyRecordService currencyRecordService;
    @Autowired
    private UserFeign userFeign;

    //购买凭证验证地址
    private static final String certificateUrl = "https://buy.itunes.apple.com/verifyReceipt";

    //测试的购买凭证验证地址
    private static final String certificateUrlTest = "https://sandbox.itunes.apple.com/verifyReceipt";
    //6块
    private static final String bundleId = "com.jinruancloud.JinRuanEdu10";

    /**
     * 重写X509TrustManager
     */
    private static TrustManager myX509TrustManager = new X509TrustManager() {

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {

        }

        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {

        }
    };

    /**
     * 接收iOS端发过来的购买凭证
     * 充值成功后更新达人币
     *
     * @param userId
     * @param receipt
     * @param chooseEnv
     */
    @RequestMapping("/setIapCertificate")
    @ResponseBody
    public String setIapCertificate(String userId, String receipt, boolean chooseEnv) {
        if (StringUtils.isEmpty(userId) || StringUtils.isEmpty(receipt)) {
            return null;
        }
        String url = null;
        url = chooseEnv == true ? certificateUrl : certificateUrlTest;
        final String certificateCode = receipt;
        if (StringUtils.isNotEmpty(certificateCode)) {
            String result = sendHttpsCoon(url, certificateCode);
            JSONObject jsonObject = JSON.parseObject(result);
            Integer status = jsonObject.getInteger("status");
            if (status == 0) {
                String receiptJr = jsonObject.getString("receipt");
                JSONObject receiptJson = JSON.parseObject(receiptJr);
                JSONArray inapp = receiptJson.getJSONArray("in_app");
                JSONObject sdata = (JSONObject) inapp.get(0);
                String productId = sdata.getString("product_id");
                String pro = productId.substring(2, productId.length());
                int price = Integer.parseInt(pro);
                //UserAccount userAccount = userAccountService.selectUserAccountByUserId(userId);
                //if (Objects.isNull(userAccount)) {
                //    UserAccount userAccountParam = new UserAccount();
                //    int i = userAccountService.insertUserAccount(userAccountParam);
                //}
                //Integer currency = userAccount.getCurrency();
                //UserAccount uccount = new UserAccount();
                //uccount.setUserId(userId);
                //uccount.setCurrency(currency + price * 10);

                //修改用户达人币
                Map<String, Object> login = userFeign.selectByUserId(Integer.parseInt(userId));
                if (login.size() > 0) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("id", Integer.parseInt(userId));
                    //用戶現有达人币
                    BigDecimal price1 = new BigDecimal(login.get("price").toString());
                    //map.put("price", price1 + price * 10);
                    map.put("price", price1.add(new BigDecimal(price * 10)));
                    //userFeign.updataByUserId(map);
                    userFeign.updatePriceByUserId(Integer.parseInt(userId), price1.add(new BigDecimal(price * 10)));
                }
                //int sqlr = userAccountService.updateUserAccount(uccount);
                CurrencyRecord rencyRecord = new CurrencyRecord();
                String currencyId = UUIDUtils.getByUUId();
                rencyRecord.setCurrencyId(currencyId);
                rencyRecord.setCreateTime(new Date());
                rencyRecord.setStatus("1");
                rencyRecord.setUserId(userId);
                //充值
                rencyRecord.setTrxType("5");
                rencyRecord.setBillId(currencyId);
                rencyRecord.setCurrency(new BigDecimal(price * 10));
                rencyRecord.setRemark("苹果端达人币充值");
                int res = currencyRecordService.insertCurrencyRecord(rencyRecord);
                //if (sqlr == 1 && res == 1) {
                if (res == 1) {
                    return sendHttpsCoon(url, certificateCode);
                } else {
                    return null;
                }
            }
            return null;
        } else {
            return null;
        }
    }

    /**
     * 发送请求
     *
     * @param url
     * @param
     * @return
     */
    private String sendHttpsCoon(String url, String code) {
        if (url.isEmpty()) {
            return null;
        }
        try {
            //设置SSLContext
            SSLContext ssl = SSLContext.getInstance("SSL");
            ssl.init(null, new TrustManager[]{myX509TrustManager}, null);

            //打开连接
            HttpsURLConnection conn = (HttpsURLConnection) new URL(url).openConnection();
            //设置套接工厂
            conn.setSSLSocketFactory(ssl.getSocketFactory());
            //加入数据
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setRequestProperty("Content-type", "application/json");

            JSONObject obj = new JSONObject();
            obj.put("receipt-data", code);

            BufferedOutputStream buffOutStr = new BufferedOutputStream(conn.getOutputStream());
            buffOutStr.write(obj.toString().getBytes());
            buffOutStr.flush();
            buffOutStr.close();

            //获取输入流
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

            String line = null;
            StringBuffer sb = new StringBuffer();
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            return sb.toString();

        } catch (Exception e) {
            return null;
        }
    }

}
